<?php
class Model_Category_XML {
    protected $_tableName = 'category';
    protected $_XMLfile;
    public function __construct()
    {
        $this->_XMLfile = $_SERVER['DOCUMENT_ROOT'] . '/data/products.xml';
    }
    
    public function parse()
    {
        $this->_truncate();
        $dom = new DOMDocument();
        $dom->load($this->_XMLfile);
        $elements = $dom->getElementsByTagName('КоммерческаяИнформация');
        $catalog =  $elements->item(0)->getElementsByTagName('Каталог');
        $i = 0; 
        foreach($catalog as $item){
            $categorys =  $catalog->item($i)->getElementsByTagName('Группа');
            $j=0;
            $query = "INSERT INTO category (id, name , parent) VALUES ";
            foreach ($categorys as $category){
                if($j != 0) $query .=', ';
                $name =  $categorys->item($j)->getAttribute('Наименование');
                $id = explode('ID',$categorys->item($j)->getAttribute('Идентификатор'));
                $parent  =explode('ID',$categorys->item($j)->getAttribute('Родитель'));
                $id = $id[1];
                $parent = $parent[1];
                $query .= "('$id', '{$name}', '$parent' )";
                $j++;
            }

            $i++;   
        }
        Zend_Registry::get('db')->query($query);
        return $i;
    }
    
    protected function _truncate()
    {
        Zend_Registry::get('db')->getConnection()->exec('truncate table ' . $this->_tableName);
    }
}